﻿using System.Windows;
using System.Windows.Controls;

namespace Lib.WPF.Dependents {
    /// <summary>
    /// 
    /// </summary>
    public class Password {

        /// <summary>
        /// 
        /// </summary>
        public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(Password), new FrameworkPropertyMetadata("", new PropertyChangedCallback(OnPropertyChanged)));
        /// <summary>
        /// 
        /// </summary>
        public static string GetPassword(DependencyObject e) => (string)e.GetValue(PasswordProperty);
        /// <summary>
        /// 
        /// </summary>
        public static void SetPassword(DependencyObject e, string Value) => e.SetValue(PasswordProperty, Value);
        /// <summary>
        /// 
        /// </summary>
        private static void OnPropertyChanged(DependencyObject e, DependencyPropertyChangedEventArgs Args) {
            if(e is PasswordBox Box) {
                Box.PasswordChanged -= Password_PasswordChanged;
                if (!isRenovate) {
                    Box.Password = Args.NewValue?.ToString();
                }
                Box.PasswordChanged += Password_PasswordChanged;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        static bool isRenovate = false;
        /// <summary>
        /// 
        /// </summary>
        private static void Password_PasswordChanged(object Sender, RoutedEventArgs Args) {
            if (Sender is PasswordBox Box) {
                isRenovate = true;
                SetPassword(Box, Box.Password);
                isRenovate = false;
            }
        }
    }
}
